package com.example.mvvmdemo.ui.adapter;

import com.example.mvvmdemo.AppApplication;
import com.example.mvvmdemo.R;
import com.example.mvvmdemo.databinding.ItemListBinding;
import com.example.mvvmdemo.ui.model.ListVm;
import com.example.mvvmdemo.ui.viewmodel.ListItemViewModel;

import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {

    private List<ListVm> data;

    public ListAdapter() {
        this.data = new ArrayList<>();
    }

    public void setData(List<ListVm> data) {
        this.data = data;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemListBinding binding = DataBindingUtil
            .inflate(LayoutInflater.from(parent.getContext()), R.layout.item_list, parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.bindData(data.get(position));
    }

    @Override
    public int getItemCount() {
        return data == null ? 0 : data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private final ItemListBinding binding;

        @Inject
        ListItemViewModel listItemViewModel;

        public ViewHolder(ItemListBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
            ((AppApplication) itemView.getContext().getApplicationContext()).getApplicationComponent()
                .inject(this);
        }

        void bindData(ListVm model) {
            listItemViewModel.setModel(model);
            binding.setViewModel(listItemViewModel);
            binding.executePendingBindings();
        }
    }
}
